/*************************************************************************
    > File Name: client.cpp
    > Author: Lancer
    > Mail: 18826075768@163.com
************************************************************************/

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <string.h>
#include <sys/shm.h>
#include <errno.h>

#define SEM_KEY 4001
#define SHM_KEY 5678

using namespace std;

union semun{
    int val;
};

int main(){
    int semid, shmid;
    shmid = shmget(SHM_KEY, sizeof(int), IPC_CREAT | 0666);
    if(shmid < 0){
        fprintf(stderr, "shmget failed!\n");
        exit(EXIT_FAILURE);
    }

    void* ptr;
    ptr = shmat(shmid, NULL, 0);
    if(ptr == (void*)-1){
        fprintf(stderr, "shmat failed!\n");
        exit(EXIT_FAILURE);
    }

    int* data = (int*)ptr;
    semid = semget(SEM_KEY, 2, IPC_CREAT | 0666);
    union semun semun1;
    semun1.val = 0;
    semctl(semid, 0, SETVAL, semun1);
    semun1.val = 1;
    semctl(semid, 1, SETVAL, semun1);

    struct sembuf sembuf1;
    while(1){
        sembuf1.sem_num = 0;
        sembuf1.sem_op = -1;
        sembuf1.sem_flg = SEM_UNDO;
        semop(semid, &sembuf1, 1);
        printf("the NUM: %d\n", *data);
        sembuf1.sem_num = 1;
        sembuf1.sem_op = 1;
        sembuf1.sem_flg = SEM_UNDO;
        semop(semid, &sembuf1, 1);
    }
    return 0;
}